<template>
  <div class="user-profile-container">
    <div class="user-layout">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <UserSidebar />
      </div>
      
      <!-- 内容区 -->
      <div class="content">
        <div class="page-header">
          <h1>个人中心</h1>
          <p>在这里管理您的个人信息和账号安全</p>
        </div>
        
        <el-card class="profile-card">
          <el-tabs v-model="activeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-form 
                ref="profileFormRef" 
                :model="profileForm" 
                :rules="profileRules" 
                label-width="100px"
                :disabled="!isEditing"
              >
                <!-- 头像显示区 -->
                <div class="avatar-container">
                  <el-avatar 
                    :size="100" 
                    :src="profileForm.avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'" 
                  />
                  <div v-if="isEditing" class="avatar-upload">
                    <el-upload
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      accept="image/*"
                      :on-change="handleAvatarChange"
                    >
                      <el-button type="primary" size="small">上传头像</el-button>
                    </el-upload>
                  </div>
                </div>
                
                <el-form-item label="用户名">
                  <el-input v-model="profileForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="profileForm.nickname" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="用户类型">
                  <el-input v-model="profileForm.userTypeText" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input v-model="profileForm.phone" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="profileForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="profileForm.gender">
                    <el-radio :label="0">男</el-radio>
                    <el-radio :label="1">女</el-radio>
                    <el-radio :label="2">保密</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="!isEditing">
                  <el-button type="primary" @click="enableEdit">修改个人信息</el-button>
                </el-form-item>
                <el-form-item v-else>
                  <el-button type="primary" @click="submitProfile" :loading="loading">保存修改</el-button>
                  <el-button @click="cancelEdit">取消</el-button>
                </el-form-item>
                
                <!-- 调试信息 -->
                <el-divider content-position="center">用户数据调试</el-divider>
                <div class="debug-info">
                  <h4>localStorage原始数据：</h4>
                  <pre>{{ rawUserInfo }}</pre>
                  
                  <h4>表单数据：</h4>
                  <pre>{{ JSON.stringify(profileForm, null, 2) }}</pre>
                  
                  <el-button type="primary" size="small" @click="reloadUserInfo">重新加载用户数据</el-button>
                </div>
              </el-form>
            </el-tab-pane>
            
            <!-- 账号安全 -->
            <el-tab-pane label="账号安全" name="security">
              <div class="security-items">
                <div class="security-item">
                  <div class="security-content">
                    <h3>登录密码</h3>
                    <p>定期更换密码可以保护您的账号安全</p>
                  </div>
                  <div class="security-action">
                    <el-button type="primary" @click="showPasswordDialog">修改密码</el-button>
                  </div>
                </div>
                
                <div class="security-item">
                  <div class="security-content">
                    <h3>手机绑定</h3>
                    <p>已绑定手机：{{ maskPhone(profileForm.phone) }}</p>
                  </div>
                  <div class="security-action">
                    <el-button type="info">更换手机</el-button>
                  </div>
                </div>
                
                <div class="security-item">
                  <div class="security-content">
                    <h3>邮箱绑定</h3>
                    <p>{{ profileForm.email ? `已绑定邮箱：${maskEmail(profileForm.email)}` : '未绑定邮箱地址' }}</p>
                  </div>
                  <div class="security-action">
                    <el-button type="info">{{ profileForm.email ? '更换邮箱' : '绑定邮箱' }}</el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialog" title="修改密码" width="500px">
      <el-form 
        ref="passwordForm" 
        :model="passwordForm" 
        :rules="passwordRules" 
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            show-password
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            show-password
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            show-password
            placeholder="请确认新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialog = false">取消</el-button>
          <el-button type="primary" @click="submitPassword" :loading="passwordLoading">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '@/utils/auth'
import UserSidebar from '../components/UserSidebar.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单相关
const profileForm = ref({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  gender: 0,
  avatar: '',
  userTypeText: ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 状态变量
const activeTab = ref('basic')
const isEditing = ref(false)
const loading = ref(false)
const passwordDialog = ref(false)
const passwordLoading = ref(false)
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const rawUserInfo = ref('未获取到数据')

// 表单验证规则
const profileRules = {
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 启用编辑模式
const enableEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  // 重置表单
  initUserProfile()
}

// 提交个人信息修改
const submitProfile = () => {
  profileFormRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      
      // 保存到localStorage
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const updatedUserInfo = {
          ...userInfo,
          nickname: profileForm.value.nickname,
          email: profileForm.value.email,
          gender: profileForm.value.gender,
          avatar: profileForm.value.avatar
          // userTypeText 不需要保存，因为会基于 userType 自动生成
        }
        localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
        
        // 更新调试信息显示
        rawUserInfo.value = JSON.stringify(updatedUserInfo)
        
        // 模拟API调用
        setTimeout(() => {
          ElMessage.success('个人信息修改成功')
          isEditing.value = false
          loading.value = false
        }, 800)
      } catch (error) {
        console.error('保存用户信息失败:', error)
        ElMessage.error('保存用户信息失败')
        loading.value = false
      }
    }
  })
}

// 显示修改密码对话框
const showPasswordDialog = () => {
  passwordDialog.value = true
  // 重置表单
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

// 提交密码修改
const submitPassword = () => {
  passwordFormRef.value?.validate((valid) => {
    if (valid) {
      passwordLoading.value = true
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('密码修改成功')
        passwordDialog.value = false
        passwordLoading.value = false
      }, 800)
    }
  })
}

// 初始化用户信息
const initUserProfile = () => {
  try {
    // 使用auth.js的getUserInfo函数获取用户信息
    const userInfo = getUserInfo()
    
    // 直接从localStorage获取原始数据用于调试显示
    const userInfoStr = localStorage.getItem('userInfo')
    rawUserInfo.value = userInfoStr || '未获取到数据'
    
    console.log('从getUserInfo获取到的用户数据:', userInfo)
    
    if (userInfo) {
      // 将userInfo数据映射到profileForm
      profileForm.value.username = userInfo.username || ''
      profileForm.value.nickname = userInfo.nickname || ''
      profileForm.value.phone = userInfo.phone || ''
      profileForm.value.email = userInfo.email || ''
      profileForm.value.userTypeText = userInfo.userTypeText || ''
      profileForm.value.avatar = userInfo.avatar || ''
      
      // 处理性别值，将字符串转为数字
      if (userInfo.gender) {
        if (userInfo.gender === '1' || userInfo.gender === 1) {
          profileForm.value.gender = 1  // 男
        } else if (userInfo.gender === '2' || userInfo.gender === 2) {
          profileForm.value.gender = 2  // 女
        } else {
          profileForm.value.gender = 0  // 保密
        }
      } else {
        profileForm.value.gender = 0  // 默认保密
      }
      
      console.log('初始化后的表单数据:', profileForm.value)
    } else {
      console.error('未找到用户信息')
      ElMessage.warning('未找到用户信息，请重新登录')
      // 没有用户信息时跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    }
  } catch (error) {
    console.error('初始化用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

// 手机号码脱敏
const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.toString().replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return ''
  const parts = email.split('@')
  if (parts.length !== 2) return email
  
  let username = parts[0]
  if (username.length > 3) {
    username = username.substring(0, 3) + '****'
  } else {
    username = username.substring(0, 1) + '****'
  }
  
  return username + '@' + parts[1]
}

// 处理头像变更
const handleAvatarChange = (file) => {
  if (!file) return;
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件!');
    return;
  }
  
  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return;
  }
  
  // 读取文件并预览
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    profileForm.value.avatar = reader.result;
  };
}

// 手动重新加载用户信息
const reloadUserInfo = () => {
  initUserProfile();
  ElMessage.success('重新加载用户数据成功');
}

// 初始化
onMounted(() => {
  initUserProfile()
})
</script>

<style lang="scss" scoped>
.user-profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .avatar-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30px;
    
    .el-avatar {
      margin-bottom: 15px;
      border: 3px solid #f0f2f5;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .avatar-upload {
      margin-top: 10px;
    }
  }
  
  .user-layout {
    display: flex;
    gap: 20px;
    
    .sidebar {
      width: 250px;
      flex-shrink: 0;
    }
    
    .content {
      flex: 1;
      
      .page-header {
        margin-bottom: 20px;
        
        h1 {
          font-size: 24px;
          color: #333;
          margin-bottom: 8px;
        }
        
        p {
          color: #666;
          font-size: 14px;
          margin: 0;
        }
      }
    }
  }
  
  .profile-card {
    margin-bottom: 20px;
  }
  
  .security-items {
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .security-content {
        h3 {
          margin: 0 0 8px 0;
          font-size: 16px;
          color: #333;
        }
        
        p {
          margin: 0;
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
  
  .debug-info {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-top: 15px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
      font-size: 14px;
    }
    
    pre {
      margin: 0;
      white-space: pre-wrap;
      font-size: 12px;
      max-height: 200px;
      overflow: auto;
    }
  }
}

@media (max-width: 768px) {
  .user-profile-container {
    .user-layout {
      flex-direction: column;
      
      .sidebar {
        width: 100%;
      }
    }
  }
}
</style> 